/**
 * 
 */
package sv.gob.mh.dgii.security;

import javax.naming.NamingException;
import org.springframework.dao.DataAccessException;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.search.LdapUserSearch;
import org.springframework.security.ldap.userdetails.Person;


/**
 * @author jose.escobar
 *
 */
public class CustomUserDetailsService implements UserDetailsService {
	
	private LdapUserSearch userSearch;

	/* (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
          DirContextOperations user = userSearch.searchForUser(username);
          
          System.out.println("loadUser");

          Person.Essence person = new Person.Essence(user);
          try {
			person.setDescription(user.getAttributes("").get("displayname").get().toString());
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
          person.setUsername(username);

          return person.createUserDetails();
	}

	public LdapUserSearch getUserSearch() {
		return userSearch;
	}

	public void setUserSearch(LdapUserSearch userSearch) {
		this.userSearch = userSearch;
	}
	
}
